<template>
  <div class="modal">
    <t-dialog
      v-model:visible="state.show"
      @close="action.close(false)"
      @closed="onClosed"
      :header="$t('common.modelCreateView.headerTitle')"
      :closeOnEscKeydown="false"
      :closeOnOverlayClick="false"
    >
      <!-- 单个视频上传 -->
      <ModalBox
        v-if="!state.batchMode"
        class="modal-box"
        v-model="state.form"
        @batch-selected="action.handleBatchSelected"
      />

      <!-- 批量上传模式 -->
<!--      <div v-else class="batch-upload-container">-->
<!--        <div class="batch-header">-->
<!--          <span class="label">{{ $t('common.modelCreateView.batchModeTitle') }}</span>-->
<!--          <t-button size="small" theme="default" @click="action.cancelBatchMode">-->
<!--            {{ $t('common.button.cancel') }}-->
<!--          </t-button>-->
<!--        </div>-->

<!--        <div class="batch-videos">-->
<!--          <div-->
<!--            v-for="(video, index) in state.batchVideos"-->
<!--            :key="index"-->
<!--            class="video-item"-->
<!--          >-->
<!--            <div class="video-preview">-->
<!--              <video :src="video.path" />-->
<!--              <div class="video-actions">-->
<!--                <t-button-->
<!--                  size="small"-->
<!--                  theme="default"-->
<!--                  variant="text"-->
<!--                  @click="action.removeVideo(index)"-->
<!--                >-->
<!--                  <t-icon name="delete" />-->
<!--                </t-button>-->
<!--                <t-button-->
<!--                  size="small"-->
<!--                  class="sync-button"-->
<!--                  @click="action.syncVideoToLibrary(index)"-->
<!--                >-->
<!--                  {{ $t('common.modelCreateView.syncToLibrary') }}-->
<!--                </t-button>-->
<!--              </div>-->
<!--            </div>-->
<!--            <t-input-->
<!--              v-model="video.name"-->
<!--              size="small"-->
<!--              :placeholder="$t('common.input.batchNamePlaceholder')"-->
<!--            />-->
<!--            <div class="video-status">-->
<!--              <t-tag v-if="video.synced" theme="success">-->
<!--                {{ $t('common.modelCreateView.syncedTag') }}-->
<!--              </t-tag>-->
<!--              <div v-if="video.categoryInfo" class="category-path">-->
<!--                {{ video.categoryInfo.categoryPath }}-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->

      <template #footer>
        <div class="dialog-footer">
          <span class="batch-count" v-if="state.batchMode">
            {{ $t('common.modelCreateView.selectedCount', { count: state.batchVideos.length }) }}
          </span>
          <t-button @click="action.submit" :loading="state.loading.submit">
            {{ $t('common.modelCreateView.submitButtonText') }}
          </t-button>
        </div>
      </template>
    </t-dialog>
  </div>
  <ModalFinished ref="modalFinished" />
</template>

<script setup>
import { reactive, watchEffect, ref } from 'vue'
import ModalBox from './ModalBox.vue'
import ModalFinished from '../ModalFinished.vue'
import { isBoolean, isObject } from 'lodash-es'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { addModel } from '@renderer/api'

const { t } = useI18n()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  onClose: {
    type: Function,
    default: () => {}
  },
  onClosed: {
    type: Function,
    default: () => {}
  }
})

const modalFinished = ref(null)

const state = reactive({
  show: false,
  loading: {
    submit: false
  },
  form: {
    uploadInfo: {
      videoPath: ''
    },
    name: '',
    language: ''
  },
  batchMode: false,
  batchVideos: [],
  categoryDialogVisible: false,
  currentSyncVideo: null,
  currentSyncIndex: -1
})

watchEffect(() => {
  state.show = props.visible
})

const action = {
  check() {
    if (state.batchMode) {
      // 批量模式检查
      if (state.batchVideos.length === 0) {
        MessagePlugin.error(t('common.message.noBatchVideos'))
        return false
      }

      const emptyNames = state.batchVideos.filter(v => !v.name.trim())
      if (emptyNames.length > 0) {
        MessagePlugin.error(t('common.message.batchVideoNameRequired'))
        return false
      }

      return true
    } else {
      // 单个视频模式检查
      const { name, uploadInfo, language } = state.form
      if (!name) {
        MessagePlugin.error('请输入模特名称')
        return false
      }
      // if (!language) {
      //   MessagePlugin.error('请选择语言')
      //   return false
      // }
      if (!uploadInfo.videoPath) {
        MessagePlugin.error('请上传拍摄好的原始视频')
        return false
      }
      return true
    }
  },

  async submit() {
    if (!action.check()) return
    state.loading.submit = true

    try {
      let isOK = false

      if (state.batchMode) {
        // 批量提交
        // isOK = await addModelBatch(
        //   state.batchVideos.map(video => ({
        //     name: video.name,
        //     videoPath: video.path
        //   }))
        // )
      } else {
        // 单个提交
        const { name, uploadInfo, language } = state.form
        // console.log(name)
        // console.log(JSON.stringify(uploadInfo))
        // console.log(language)
        let lang = language === '' ? 'zh' : language
        if (uploadInfo.synced){
          isOK = await addModel({
              name,
              videoPath: uploadInfo.videoPath,
              synced: uploadInfo.synced,
              primaryCategoryId: uploadInfo.categoryInfo.primaryCategoryId,
              secondaryCategoryId: uploadInfo.categoryInfo.secondaryCategoryId,
              tertiaryCategoryId: uploadInfo.categoryInfo.tertiaryCategoryId,
              lang,
            })
        }else {
          isOK = await addModel({
            name,
            videoPath: uploadInfo.videoPath,
            lang,
          })
        }
      }

      if (isOK) {
        const result = await modalFinished.value.show(state.form.uploadInfo.synced)
        action.close({ isSubmitOK: true, isSubmitOK_toSee: result.isToSee, synced: result.synced })
      } else {
        throw new Error('制作失败~')
      }
    } catch (err) {
      MessagePlugin.error(err.toString() || '制作失败~')
    } finally {
      state.loading.submit = false
    }
  },

  handleBatchSelected(videos) {
    state.batchMode = true
    state.batchVideos = videos.map(path => ({
      path,
      name: '',
      synced: false,
      categoryInfo: null
    }))
  },

  cancelBatchMode() {
    state.batchMode = false
    state.batchVideos = []
    state.form = {
      uploadInfo: { videoPath: '' },
      name: ''
    }
  },

  removeVideo(index) {
    state.batchVideos.splice(index, 1)
    if (state.batchVideos.length === 0) {
      action.cancelBatchMode()
    }
  },

  close(params = false) {
    const result = {
      isSubmitOK: false,
      isSubmitOK_toSee: false,
      synced: state.form.uploadInfo.synced,
    }
    if (isBoolean(params)) {
      result.isSubmitOK = params
    } else if (isObject(params)) {
      Object.assign(result, params)
    }
    state.show = false
    props.onClose(result)
  }
}
</script>

<style lang="less" scoped>
.modal {
  --td-text-color-primary: #ffffff;
  --td-bg-color-specialcomponent: #1d1e20;
  --td-bg-color-secondarycontainer: #161718;

  :deep(.t-dialog__position) {
    align-items: center;
    padding: 0;
  }

  :deep(.t-dialog) {
    padding: 0;
    width: 75vw;
    max-width: 1080px;
    overflow: hidden;
    max-height: 86vh;
    background: #1d1e20;
    box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.25);
    border-radius: 4px 4px 4px 4px;
    border: 1px solid #3f4041;
    color: #ffffff;
    display: flex;
    flex-direction: column;
  }

  :deep(.t-dialog__header) {
    padding: 16px;
    font-weight: 500;
    font-size: 14px;
    color: #ffffff;
    line-height: 16px;
  }

  :deep(.t-dialog__close) {
    color: #ffffff;

    &:hover {
      background-color: #373739;
    }
  }

  :deep(.t-dialog__body) {
    padding: 20px 40px;
    color: #ffffff;
  }

  :deep(.t-dialog__footer) {
    padding: 24px 40px;
    border-top: 1px solid #000000;
  }

  .batch-upload-container {
    .batch-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .label {
        font-weight: 500;
        font-size: 14px;
        color: #ffffff;
      }
    }

    .batch-videos {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 16px;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 2px;
      }

      .video-item {
        display: flex;
        flex-direction: column;
        gap: 8px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 8px;
        padding: 8px;

        .video-preview {
          position: relative;
          height: 140px;
          border-radius: 4px;
          overflow: hidden;

          video {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .video-actions {
            position: absolute;
            bottom: 8px;
            right: 8px;
            display: flex;
            gap: 8px;
            opacity: 0;
            transition: opacity 0.2s;

            .sync-button {
              background-color: rgba(67, 74, 249, 0.8);
              color: #ffffff;
            }
          }

          &:hover .video-actions {
            opacity: 1;
          }
        }

        .video-status {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 12px;

          .category-path {
            color: rgba(255, 255, 255, 0.7);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .batch-count {
      font-size: 13px;
      color: rgba(255, 255, 255, 0.7);
    }
  }
}
</style>
